using System.Collections.Generic;
using System.Linq;
using AesEverywhere;
using I2.Loc;
using UnityEngine;
using UnityEngine.Analytics;
using UnityEngine.Events;
using UnityEngine.UI;

public class CampaignGame : MonoBehaviour
{
	public static CampaignGame Instance;

	[Header("Test")]
	public bool isTest;

	public int testDay;

	public string testSuit;

	public string testPrimaryWeapon;

	public string testSecondaryWeapon;

	public string testMeleeWeapon;

	public int testFixHealth;

	[Range(2f, 5f)]
	public float testStr;

	[Range(2f, 5f)]
	public float testSpd;

	[Range(1f, 5f)]
	public int testKick;

	[Header("Main")]
	public bool isPlayground;

	public Ranking ranking;

	public SmoothFollow camFollower;

	public int day;

	public Player player;

	public float restTimePreWave;

	public float nextWaveDistance;

	public float zombieDeployDistance;

	public float startTime;

	public GridLayoutGroup itemListView;

	public Button itemButtonView;

	private bool itemShowHotKey;

	public Canvas introCanvas;

	public Canvas checkIntroCanvas;

	public Canvas controllerCanvas;

	public Canvas gameOverCanvas;

	public Canvas pauseCanvas;

	public GameObject smartwatch;

	public static Dictionary<string, Item> itemCache = new Dictionary<string, Item>();

	public int maxZombieInMap = 20;

	public GameObject deployButton;

	public RectTransform deployButtonProgressRect;

	public Text deployButtonCount;

	private Vector2 deployProgressAnchorMax;

	public AnimationCurve zombiePreWaveByDay;

	private int minZombiePreWave;

	public int maxWave = 5;

	public int waveTotal;

	public int waveCount;

	public float waveClearTime;

	public bool isWaveCleared;

	public int zombieCount;

	public int zombieTotal;

	public static int zombieKillCount = 0;

	public List<Zombie> zombies = new List<Zombie>();

	public float lastWaveX;

	public float nextWaveTime;

	private bool finished;

	public GameObject toolsView;

	public GameObject toolsConfirmView;

	public Button placingToolItemButtonView;

	public static int dayIncome = 0;

	public static bool exited = false;

	public Animator animator;

	public BackgroundMusic backgroundMusic;

	public AudioSource audioSource;

	public AudioClip placeToolFailAudio;

	public AudioClip placeToolSuccessAudio;

	public Text dayText;

	public Text statsText;

	public List<Zombie> zombieSeed = new List<Zombie>();

	public Gradient envSkyColor;

	public Gradient envLightColor;

	public Gradient envFogColor;

	public Light envLight;

	public Material envMaterial;

	public SpriteRenderer envSky;

	public SpriteRenderer[] envFogs;

	public int envStyleMaxDay = 2;

	public string campaignDataCacheJson;

	public GameObject retryButton;

	public int retryGold;

	public IAPManager iapManager;

	public int storyState;

	public Transform storyDialogueList;

	public GameObject dialogueButton;

	public int easyEndDay = 15;

	public int hardcoreEndDay = 30;

	public static float framerate;

	public UnityEvent onWaveStart;

	private float waveStartTime;

	private bool isSkipFinishScene;

	private int defaultResolutionWidth;

	private int defaultResolutionHeight;

	public bool ItemShowHotKey
	{
		get
		{
			return itemShowHotKey;
		}
		set
		{
			itemShowHotKey = value;
		}
	}

	public bool IsSkipFinishScene
	{
		get
		{
			return isSkipFinishScene;
		}
		set
		{
			isSkipFinishScene = value;
		}
	}

	private void Awake()
	{
		Instance = this;
		if (Config.initialized)
		{
			new Config().Init();
		}
		if (!Application.isEditor)
		{
			isTest = false;
		}
		if (isTest)
		{
			DO.Campaign.day = testDay;
			DO.Campaign.suit = testSuit;
			DO.Campaign.primaryWeapon = testPrimaryWeapon;
			DO.Campaign.secondaryWeapon = testSecondaryWeapon;
			DO.Campaign.meleeWeapon = testMeleeWeapon;
			DO.Campaign.playerStrength = testStr;
			DO.Campaign.playerSpeed = testSpd;
			DO.Campaign.playerKickTotal = testKick;
			Debug.LogWarning("Test Mode ON");
		}
		if (!isPlayground)
		{
			SetEnvStyle();
			day = DO.Campaign.day;
		}
		startTime = Time.time;
		exited = false;
		dayIncome = 0;
		zombieKillCount = 0;
		if (!isPlayground)
		{
			animator.Play("GameStart");
		}
		else
		{
			dayText.text = "Playground";
		}
		if (isPlayground)
		{
			restTimePreWave = DO.Playground.waveInterval;
		}
		zombies.Clear();
	}

	public Button AddItemButtonToListView(Item item)
	{
		string key = item.name.Replace("(Clone)", "");
		List<string> availableItems = DO.Campaign.availableItems;
		GameObject pet = null;
		if (item.type == ItemType.Pet)
		{
			if (isPlayground && (bool)item.prefab.GetComponent<Chicken>())
			{
				return null;
			}
			pet = Object.Instantiate(item.prefab);
			pet.transform.position = player.transform.position;
			if ((bool)item.prefab.GetComponent<Chicken>())
			{
				return null;
			}
			if ((bool)item.prefab.GetComponent<Cat>() && !isPlayground)
			{
				return null;
			}
		}
		Transform transform = item.transform.Find("Sprite");
		if (!transform)
		{
			transform = item.transform.Find("Mask/Sprite");
		}
		Sprite sprite = transform.GetComponent<SpriteRenderer>().sprite;
		Button _itemButtonView = Object.Instantiate(itemButtonView, itemListView.transform);
		Image component = _itemButtonView.transform.Find("Image").GetComponent<Image>();
		_itemButtonView.name = key;
		component.sprite = sprite;
		_itemButtonView.transform.Find("HotKey").gameObject.SetActive(value: false);
		if (item.type == ItemType.Tool)
		{
			Text component2 = _itemButtonView.transform.Find("Count").GetComponent<Text>();
			component2.text = availableItems.Where((string s) => s == key).Count().ToString();
			if (isPlayground || _itemButtonView.name == "Smartwatch")
			{
				component2.text = null;
			}
			_itemButtonView.onClick.AddListener(delegate
			{
				if (!player.isPlacingItem)
				{
					ChoosePlaceTools(_itemButtonView);
				}
			});
		}
		if (item.type == ItemType.Pet && pet != null)
		{
			if (isPlayground && (bool)item.prefab.GetComponent<Chicken>())
			{
				return null;
			}
			if ((bool)item.prefab.GetComponent<Chicken>())
			{
				return null;
			}
			Image _itemButtonImg = _itemButtonView.GetComponent<Image>();
			_itemButtonView.onClick.AddListener(delegate
			{
				SwitchPetState(pet, _itemButtonImg);
			});
			if (isPlayground && PlayerPrefs.GetInt("PlaygroundPetState_" + pet.name, 1) == 1 != pet.gameObject.activeSelf)
			{
				SwitchPetState(pet, _itemButtonImg);
			}
		}
		return _itemButtonView;
	}

	private void Start()
	{
		if (DO.Campaign.day > DO.Player.reachedDay)
		{
			DO.Player.reachedDay = DO.Campaign.day;
		}
		SaveLoad.SaveString("Player", JsonUtility.ToJson(DO.Player));
		if (isPlayground)
		{
			Analytics.CustomEvent("CampaignGameStart", new Dictionary<string, object>
			{
				{
					"player_id",
					DO.Player.playerGuid
				},
				{
					"campaign_id",
					DO.Campaign.campaignGuid
				},
				{
					"day",
					DO.Campaign.day
				}
			});
		}
		else
		{
			Analytics.CustomEvent("PlaygroundGameStart", new Dictionary<string, object> {
			{
				"player_id",
				DO.Player.playerGuid
			} });
		}
		restTimePreWave = Mathf.Max(restTimePreWave - (float)(DO.Campaign.day / 20), 2f);
		nextWaveTime = Time.time + restTimePreWave + 2f;
		if (!isPlayground)
		{
			SetZombieSeed();
		}
		SwapPool.Clear();
		GameObject gameObject = GameObject.Find("BackgroundMusic");
		if ((bool)gameObject)
		{
			gameObject.GetComponent<BackgroundMusic>().active = false;
		}
		waveTotal = Mathf.Clamp(Mathf.CeilToInt(day / 10) + 3, 3, maxWave);
		if (!isPlayground)
		{
			minZombiePreWave = Mathf.CeilToInt(zombiePreWaveByDay.Evaluate(day - 1));
		}
		Item[] array = (from x in Resources.LoadAll("Items/", typeof(Item)).Cast<Item>().ToArray()
						orderby -x.inGamePriority
						select x).ToArray();
		if (itemCache.Count == 0)
		{
			Item[] array2 = array;
			foreach (Item item in array2)
			{
				itemCache.Add(item.name, item);
			}
		}
		List<string> list = DO.Campaign.availableItems;
		if (isPlayground)
		{
			list = DO.Player.reachedItems;
		}
		int num = 1;
		foreach (KeyValuePair<string, Item> item2 in itemCache)
		{
			if (!list.Contains(item2.Key) || (item2.Value.type != ItemType.Pet && item2.Value.type != ItemType.Tool) || (isPlayground && item2.Value.name == "Smartwatch") || (!isPlayground && item2.Value.type == ItemType.Pet && item2.Key != DO.Campaign.pet))
			{
				continue;
			}
			Item component = Object.Instantiate(item2.Value).GetComponent<Item>();
			component.transform.position = Vector2.down * 10f;
			Button button = AddItemButtonToListView(component);
			if ((bool)button)
			{
				Tool component2 = component.prefab.GetComponent<Tool>();
				if (ItemShowHotKey && (bool)component2 && (bool)component2.thrownObject && num <= 9)
				{
					button.transform.Find("HotKey/Text").GetComponent<Text>().text = num.ToString();
					num++;
				}
				else
				{
					button.transform.Find("HotKey").gameObject.SetActive(value: false);
				}
			}
		}
		Vector2 vector = Vector2.zero;
		List<StageItem> list2 = new List<StageItem>();
		list2 = ((!isPlayground) ? DO.Campaign.stageItems : DO.Playground.stageItems);
		foreach (StageItem item3 in list2)
		{
			GameObject gameObject2 = Object.Instantiate(itemCache[item3.name].prefab);
			gameObject2.transform.position = item3.pos;
			if (item3.name == "CheckPoint" && item3.pos.x > vector.x)
			{
				vector = item3.pos;
			}
			if (item3.name == "Turret")
			{
				Turret component3 = gameObject2.GetComponent<Turret>();
				Weapon component4 = Object.Instantiate(itemCache[item3.usedItemName].prefab).GetComponent<Weapon>();
				component3.AddWeapon(component4);
				component3.fireTrigger.enabled = true;
			}
			gameObject2.GetComponent<Tool>().Placed();
		}
		if (vector.x > player.transform.position.x)
		{
			player.transform.position = new Vector3(vector.x, player.transform.position.y, 1f);
		}
		if (!isPlayground && DO.Campaign.day <= 1)
		{
			NextWave();
		}
		if (!isPlayground)
		{
			deployButtonCount.text = 1 + "/" + waveTotal;
		}
	}

	public void SwitchPetState(GameObject pet, Image buttonImage)
	{
		if (!pet)
		{
			return;
		}
		Tiger component2;
		Bear component3;
		Drone component4;
		Cat component5;
		if (pet.TryGetComponent<Dog>(out var component))
		{
			component.canAttack = !component.canAttack;
			if (isPlayground)
			{
				component.enabled = !component.enabled;
			}
		}
		else if (pet.TryGetComponent<Tiger>(out component2))
		{
			component2.canAttack = !component2.canAttack;
			if (isPlayground)
			{
				component2.enabled = !component2.enabled;
			}
		}
		else if (pet.TryGetComponent<Bear>(out component3))
		{
			component3.canAttack = !component3.canAttack;
			if (isPlayground)
			{
				component3.enabled = !component3.enabled;
			}
		}
		else if (pet.TryGetComponent<Drone>(out component4))
		{
			component4.canAttack = !component4.canAttack;
			if (isPlayground)
			{
				component4.enabled = !component4.enabled;
			}
		}
		else if (pet.TryGetComponent<Cat>(out component5) && isPlayground)
		{
			component5.enabled = !component5.enabled;
		}
		if (isPlayground)
		{
			GameObject gameObject = pet.transform.Find("Body").gameObject;
			bool flag = !gameObject.activeSelf;
			gameObject.SetActive(flag);
			if (pet.TryGetComponent<AudioSource>(out var component6))
			{
				component6.enabled = gameObject.activeSelf;
			}
			PlayerPrefs.SetInt("PlaygroundPetState_" + pet.name, flag ? 1 : 0);
		}
		buttonImage.color = ((buttonImage.color == Color.red) ? Color.black : Color.red);
	}

	public void ChoosePlaceTools(Button itemButtonView)
	{
		if (itemButtonView.name == "Smartwatch")
		{
			smartwatch.SetActive(value: true);
			return;
		}
		placingToolItemButtonView = itemButtonView;
		string key = itemButtonView.name;
		if (!isPlayground && int.Parse(placingToolItemButtonView.transform.Find("Count").GetComponent<Text>().text) == 0)
		{
			audioSource.PlayOneShot(placeToolFailAudio);
			player.placingTool = null;
			placingToolItemButtonView = null;
			return;
		}
		player.placingTool = Object.Instantiate(itemCache[key].prefab).GetComponent<Tool>();
		player.placingTool.transform.position = new Vector2(-100f, 100f);
		player.placingTool.OnPlace();
		toolsView.SetActive(value: false);
		toolsConfirmView.GetComponent<RectTransform>().position = itemButtonView.GetComponent<RectTransform>().position;
		toolsConfirmView.SetActive(value: true);
	}

	public void ConfirmPlaceTools()
	{
		if ((bool)Player.Instance.weapon && Player.Instance.weapon.onReload)
		{
			return;
		}
		if ((bool)player.placingTool && player.placingTool.placeable)
		{
			string itemName = placingToolItemButtonView.name;
			if ((bool)player.placingTool.thrownObject)
			{
				if (!player.placingTool.thrownObject.pickupable && !isPlayground)
				{
					DO.Campaign.availableItems.Remove(itemName);
				}
				player.isPlacingItem = true;
				if (itemName == "Banana")
				{
					player.body.animator.SetTrigger("banana");
				}
				else
				{
					player.body.animator.SetTrigger("thrownItem");
				}
			}
			else
			{
				StageItem stageItem = new StageItem();
				stageItem.name = itemName;
				stageItem.pos = player.placingTool.transform.position;
				if (!isPlayground)
				{
					if (player.placingTool.usedItemName != null)
					{
						stageItem.usedItemName = player.placingTool.usedItemName;
					}
					DO.Campaign.availableItems.Remove(itemName);
					DO.Campaign.stageItems.Add(stageItem);
				}
				else
				{
					stageItem.usedItemName = player.placingTool.usedItemName;
					if (itemName == "Turret")
					{
						for (int i = 0; i < DO.Playground.stageItems.Count; i++)
						{
							if (!(DO.Playground.stageItems[i].name == "Turret"))
							{
								continue;
							}
							DO.Playground.stageItems.RemoveAt(i);
							GameObject[] array = GameObject.FindGameObjectsWithTag("Player");
							foreach (GameObject gameObject in array)
							{
								if (gameObject.name == "Turret(Clone)" && gameObject != player.placingTool.gameObject)
								{
									Object.Destroy(gameObject);
								}
							}
						}
					}
					else if (itemName == "Milk")
					{
						for (int k = 0; k < DO.Playground.stageItems.Count; k++)
						{
							if (DO.Playground.stageItems[k].name == "Milk")
							{
								DO.Playground.stageItems.RemoveAt(k);
								break;
							}
						}
						GameObject[] array = GameObject.FindGameObjectsWithTag("Player");
						foreach (GameObject gameObject2 in array)
						{
							if (gameObject2.name == "Milk(Clone)" && gameObject2 != player.placingTool.gameObject)
							{
								Object.Destroy(gameObject2);
								break;
							}
						}
					}
					DO.Playground.stageItems.Add(stageItem);
				}
				player.isPlacingItem = true;
				if (isPlayground)
				{
					player.body.StartPlaceItem();
					player.body.EndPlaceItem();
				}
				else
				{
					player.releaseLeftHand = true;
					player.releaseRightHand = true;
					player.body.animator.SetTrigger("placeItem");
				}
			}
			if (!isPlayground)
			{
				int num = DO.Campaign.availableItems.Where((string s) => s == itemName).Count();
				if ((bool)player.placingTool.thrownObject && player.placingTool.thrownObject.pickupable)
				{
					num = 0;
				}
				placingToolItemButtonView.transform.Find("Count").GetComponent<Text>().text = num.ToString();
				if (num == 0)
				{
					placingToolItemButtonView.GetComponent<Image>().color = Color.red;
				}
			}
			toolsView.SetActive(value: true);
			toolsConfirmView.SetActive(value: false);
		}
		else
		{
			audioSource.PlayOneShot(placeToolFailAudio);
		}
		if (isPlayground)
		{
			SaveLoad.SaveString("Playground", JsonUtility.ToJson(DO.Playground));
		}
	}

	public void CancelPlaceTools()
	{
		if ((bool)player.placingTool)
		{
			Object.Destroy(player.placingTool.gameObject);
			player.placingTool = null;
			placingToolItemButtonView = null;
			toolsView.SetActive(value: true);
			toolsConfirmView.SetActive(value: false);
		}
	}

	public void Finish()
	{
		if (!isPlayground)
		{
			if (DO.Campaign.suit == "HitmanSuit")
			{
				DO.Campaign.balance += 500;
			}
			dayIncome = (int)((float)dayIncome * 0.75f) + 100;
			if (dayIncome > 3000)
			{
				dayIncome = 3000 + Random.Range(DO.Campaign.day, 1);
			}
			DO.Campaign.playerName = DO.Player.playerName;
			DO.Campaign.dayFinish = true;
			DO.Campaign.dayShoppingFinish = false;
			DO.Campaign.balance += dayIncome;
			DO.Campaign.killCount += zombieKillCount;
			DO.Campaign.dayIncome = dayIncome;
			DO.Campaign.totalIncome += dayIncome;
			DO.Campaign.playTime += Time.time - startTime;
			DO.Campaign.dayIncomeRewarded = 0;
			DO.Campaign.dayShoppingItems.Clear();
			string content = JsonUtility.ToJson(DO.Campaign);
			// if (!Application.isEditor)
			// {
			// 	StartCoroutine(Api.Post("/api.php?action=AddLog", new AES256().Encrypt(JsonUtility.ToJson(DO.Campaign), Config.encryptionKey), null));
			// }
			SaveLoad.SaveString("Campaign", content);
			if (!IsSkipFinishScene)
			{
				Initiate.Fade("CampaignShop", Color.black, 5f);
			}
			else
			{
				Initiate.Fade("CampaignShop", Color.black, 5f);
			}
			MyAdManager.Instance.MyShowEndBox();
		}
	}

	public void Gameover()
	{
		if (isPlayground)
		{
			return;
		}
		if (DO.Campaign.goldUsed > 0)
		{
			ranking.type = "gold";
			ranking.transform.Find("RowHead/Ranking").GetComponent<Text>().text += " (Gold)";
		}
		camFollower.offsetX = 1f;
		animator.Play("GameOver");
		if (DO.Campaign.availableItems.Contains("Clone"))
		{
			gameOverCanvas.transform.Find("Layout").gameObject.SetActive(value: false);
			gameOverCanvas.transform.Find("Clone").gameObject.SetActive(value: true);
			return;
		}
		statsText.text = LocalizationManager.GetTranslation("DeadStats");
		statsText.text = statsText.text.Replace("{TOTAL_DAY}", DO.Campaign.day.ToString("n0"));
		statsText.text = statsText.text.Replace("{TOTAL_KILL}", (DO.Campaign.killCount + zombieKillCount).ToString("n0"));
		statsText.text = statsText.text.Replace("{TOTAL_INCOME}", DO.Campaign.totalIncome.ToString("n0"));
		statsText.text = statsText.text.Replace("{GAME_TIME}", Mathf.Floor((DO.Campaign.playTime + Time.time - startTime) / 60f).ToString("00") + ":" + ((DO.Campaign.playTime + Time.time - startTime) % 60f).ToString("00"));
		statsText.text = statsText.text.Replace("{PLAYER_SPEED}", DO.Campaign.playerSpeed.ToString());
		statsText.text = statsText.text.Replace("{PLAYER_STRENGTH}", DO.Campaign.playerStrength.ToString());
		statsText.text = statsText.text.Replace("{PLAYER_KICK_LEVEL}", DO.Campaign.playerKickTotal.ToString());
		campaignDataCacheJson = JsonUtility.ToJson(DO.Campaign);
		if (DO.Campaign.day == 1)
		{
			retryButton.SetActive(value: false);
		}
		else
		{
			retryGold = (DO.Campaign.day - 1) * 10;
			Text component = retryButton.transform.GetChild(0).GetComponent<Text>();
			string text = LocalizationManager.GetTranslation("Retry").Replace("{GOLD}", retryGold.ToString("n0"));
			component.text = text;
		}
		DO.NewCampaign();
		Analytics.CustomEvent("CampaignGameOver", new Dictionary<string, object>
		{
			{
				"player_id",
				DO.Player.playerGuid
			},
			{
				"campaign_id",
				DO.Campaign.campaignGuid
			},
			{
				"day",
				DO.Campaign.day
			}
		});
		MyAdManager.Instance.MyShowEndBox();
	}

	public void TryAgainByClone()
	{
		if (DO.Campaign.availableItems.Contains("Clone"))
		{
			DO.Campaign.availableItems.Remove("Clone");
			DO.Campaign.playerHealth = 100f;
			SaveLoad.SaveString("Campaign", JsonUtility.ToJson(DO.Campaign));
			Initiate.Fade("CampaignPrepare", Color.black, 5f);
		}
	}

	public void TryAgainByGold()
	{
		if (DO.Player.gold < retryGold)
		{
			iapManager.Open();
			return;
		}
		Analytics.CustomEvent("CampaignGameRetryByGold", new Dictionary<string, object>
		{
			{
				"player_id",
				DO.Player.playerGuid
			},
			{
				"campaign_id",
				DO.Campaign.campaignGuid
			},
			{
				"day",
				DO.Campaign.day
			}
		});
		gameOverCanvas.enabled = false;
		SaveLoad.SaveString("Campaign", campaignDataCacheJson);
		DO.ReLoadCampaign();
		DO.Campaign.retryCount++;
		DO.Campaign.playerHealth = 100f;
		DO.Campaign.goldUsed += retryGold;
		SaveLoad.SaveString("Campaign", JsonUtility.ToJson(DO.Campaign));
		DO.Player.gold -= retryGold;
		SaveLoad.SaveString("Player", JsonUtility.ToJson(DO.Player));
		Initiate.Fade("CampaignPrepare", Color.black, 5f);
	}

	public void NewGame()
	{
		Initiate.Fade("CampaignGame", Color.black, 5f);
	}

	public static void Income(int money)
	{
		dayIncome += money;
	}

	public void SetZombieSeed()
	{
		Object[] array = Resources.LoadAll("Zombies/", typeof(Object));
		for (int i = 0; i < array.Length; i++)
		{
			Zombie component = ((GameObject)array[i]).GetComponent<Zombie>();
			int num = Mathf.RoundToInt(component.deployPriority.Evaluate(day));
			if (num > 0)
			{
				for (int j = 0; j < num; j++)
				{
					zombieSeed.Add(component);
				}
			}
		}
	}

	public void Dialogue(string name)
	{
		foreach (Transform storyDialogue in storyDialogueList)
		{
			if (storyDialogue.name == name)
			{
				storyDialogue.gameObject.SetActive(value: true);
				if (name.Contains("Driver"))
				{
					Vector2 vector = GameObject.FindGameObjectWithTag("Driver").transform.position;
					vector.y += 2.4f;
					vector.x += 0.5f;
					storyDialogue.transform.position = vector;
				}
				else if (name.Contains("Player"))
				{
					Vector2 vector2 = player.transform.position;
					vector2.y += 2.4f;
					vector2.x += 0.2f;
					storyDialogue.transform.position = vector2;
				}
			}
			else
			{
				storyDialogue.gameObject.SetActive(value: false);
			}
		}
	}

	public void DialogueWait(string name)
	{
		Debug.Log("DialogueWait");
		Dialogue(name);
		dialogueButton.SetActive(value: true);
		StopStory();
	}

	public void ContinueStory()
	{
		Debug.Log("ContinueStory");
		Dialogue(null);
		dialogueButton.SetActive(value: false);
		animator.enabled = true;
	}

	public void StopStory()
	{
		Debug.Log("StopStory");
		animator.enabled = false;
	}

	public void EndStory()
	{
		DO.Campaign.storyDone = 1;
		SaveLoad.SaveString("Campaign", JsonUtility.ToJson(DO.Campaign));
		Initiate.Fade("CampaignGame", Color.black, 5f);
	}

	public void StoryPlayerThrownAirSupport()
	{
		string key = "AirSupport";
		player.placingTool = Object.Instantiate(itemCache[key].prefab).GetComponent<Tool>();
		player.placingTool.transform.position = new Vector2(-100f, 100f);
		player.placingTool.OnPlace();
		player.isPlacingItem = true;
		player.releaseLeftHand = true;
		player.body.animator.SetTrigger("thrownItem");
	}

	public void SetStoryState(int val)
	{
		Debug.Log("SetStoryState");
		animator.enabled = true;
		storyState = val;
	}

	private void Update()
	{
		framerate = 1f / Time.smoothDeltaTime;
		_ = storyState;
		_ = 0;
	}

	private void FixedUpdate()
	{
		if (storyState > 0)
		{
			return;
		}
		if (Application.platform == RuntimePlatform.Android && (Input.GetKey(KeyCode.Home) || Input.GetKey(KeyCode.Escape) || Input.GetKey(KeyCode.Menu)))
		{
			Pause();
		}
		else
		{
			if (finished || player.isDead)
			{
				return;
			}
			if ((bool)player.placingTool)
			{
				player.placingTool.transform.position = new Vector2(player.transform.position.x + 0.2f, player.transform.position.y + 0.1f);
			}
			if (!isPlayground)
			{
				if (waveCount >= waveTotal && zombieKillCount >= zombieTotal)
				{
					if (!finished)
					{
						finished = true;
						Invoke("Finish", 2f);
						return;
					}
				}
				else if (Time.time > nextWaveTime)
				{
					NextWave();
				}
			}
			else if (Time.time > nextWaveTime)
			{
				NextWave();
			}
			if (zombieKillCount == zombieTotal && !isWaveCleared)
			{
				waveClearTime = Time.time;
				isWaveCleared = true;
				if (!isPlayground)
				{
					deployButtonCount.text = waveCount + 1 + "/" + waveTotal;
				}
				animator.Play("WaveRest");
			}
			if (zombieKillCount == zombieTotal)
			{
				_ = player.transform.position.x / (lastWaveX + nextWaveDistance);
				float x = (Time.time - waveClearTime) / (nextWaveTime - waveClearTime);
				deployProgressAnchorMax = new Vector2(x, 1f);
				deployButtonProgressRect.anchorMax = deployProgressAnchorMax;
			}
			else
			{
				nextWaveTime = Time.time + Mathf.Max(0.05f, restTimePreWave);
			}
			if (zombieTotal > zombieCount)
			{
				AddZombie();
			}
		}
	}

	public void NextWave()
	{
		if (zombieKillCount < zombieCount)
		{
			return;
		}
		waveCount++;
		if (isPlayground)
		{
			zombieTotal += DO.Playground.totalZombiePreWave;
		}
		else if (day < 5)
		{
			zombieTotal += Mathf.CeilToInt(waveCount / 10 + minZombiePreWave);
		}
		else
		{
			zombieTotal += Mathf.CeilToInt(waveCount / 2 + minZombiePreWave);
			if (waveCount == waveTotal)
			{
				zombieTotal = Mathf.CeilToInt((float)zombieTotal * 1.2f);
			}
		}
		lastWaveX = player.transform.position.x;
		isWaveCleared = false;
		if (zombieTotal > zombieKillCount)
		{
			animator.Play("WaveStart");
		}
		onWaveStart.Invoke();
		waveStartTime = Time.time;
	}

	public void AddZombie()
	{
		if (zombieSeed.Count != 0 && (isPlayground || zombies.Count < maxZombieInMap))
		{
			GameObject gameObject = Ground.groundColliders[Random.Range(0, Ground.groundColliders.Count)];
			float num = player.transform.position.x + zombieDeployDistance;
			if (Time.time - waveStartTime < 2f)
			{
				num += (float)Random.Range(0, zombies.Count * 2);
			}
			float y = gameObject.transform.position.y;
			if (isPlayground)
			{
				num = player.transform.position.x + Random.Range(zombieDeployDistance, zombieDeployDistance + (float)DO.Playground.zombieDistance);
			}
			Zombie component = Object.Instantiate(zombieSeed[Random.Range(0, zombieSeed.Count)], new Vector2(num, y), Quaternion.identity).GetComponent<Zombie>();
			component.player = player;
			component.body.SetColliderLayer(gameObject.layer);
			zombieCount++;
		}
	}

	public void Pause()
	{
		AdManager.Instance.ShowNative(0f);
		Time.timeScale = 0f;
		pauseCanvas.gameObject.SetActive(value: true);
		AudioListener.pause = true;
	}

	public void PlayAudio(AudioClip audio)
	{
		audioSource.PlayOneShot(audio);
	}

	public void Resume()
	{
		Time.timeScale = 1f;
		pauseCanvas.gameObject.SetActive(value: false);
		AudioListener.pause = false;
	}

	public void ShowIntro()
	{
		Pause();
		checkIntroCanvas.gameObject.SetActive(value: false);
		PlayerPrefs.SetInt("IntroShown", 1);
		pauseCanvas.gameObject.SetActive(value: false);
		introCanvas.gameObject.SetActive(value: true);
	}

	public void CloseIntro()
	{
		Resume();
		introCanvas.gameObject.SetActive(value: false);
	}

	public void GoToMainMenu()
	{
		Time.timeScale = 1f;
		exited = true;
		AudioListener.pause = false;
		Initiate.Fade("Main", Color.black, 5f);
	}

	public void SetEnvStyle()
	{
		float num = Mathf.Min((float)DO.Campaign.day / (float)envStyleMaxDay, 1f);
		if ((bool)envMaterial)
		{
			envMaterial.color = envLightColor.Evaluate(num * 0.8f);
		}
		if ((bool)envLight)
		{
			envLight.color = envLightColor.Evaluate(num);
		}
		if ((bool)envSky)
		{
			envSky.color = envSkyColor.Evaluate(num);
		}
		if (envFogs.Length == 0)
		{
			return;
		}
		SpriteRenderer[] array = envFogs;
		foreach (SpriteRenderer spriteRenderer in array)
		{
			if ((bool)spriteRenderer)
			{
				spriteRenderer.color = envFogColor.Evaluate(num);
			}
		}
	}
}
